package com.wsoft.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wsoft.core.service.CommonConfigService;
import com.wsoft.core.vo.ConfigQuery;
import com.wsoft.core.vo.ConfigVO;
import com.wsoft.enums.ConfigTypeEnum;
import com.wsoft.system.service.ITsConfigInfoService;
import com.wsoft.vo.config.ConfigRespVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Zhang gukai
 * @Date 2024/12/13 14:12
 */
@Service
public class CommonConfigServiceImpl implements CommonConfigService {
    @Resource
    private ITsConfigInfoService configInfoService;

    @Override
    public List<ConfigVO> getConfigList(List<ConfigQuery> queryList) {
        List<ConfigVO> result = new ArrayList<>();
        queryList.forEach(query -> {
            ConfigRespVO configByCode = configInfoService.getConfigByCode(query.getMemberId(), query.getOrgId(), query.getCode());
            result.add(Convert.convert(ConfigVO.class, configByCode));
        });
        return result;
    }

    @Override
    public Map<String, String> getConfigValue(ConfigQuery query) {
        ConfigRespVO configByCode = configInfoService.getConfigByCode(query.getMemberId(), query.getOrgId(), query.getCode());
        Map<String, String> map = new HashMap<>(12);
        if (configByCode.getType().equals(ConfigTypeEnum.JSON.getValue())) {
            JSONArray array = JSONUtil.parseArray(configByCode.getValue());
            array.forEach(item -> {
                JSONObject jsonObject = JSONUtil.parseObj(item);
                map.put(jsonObject.getStr("code"), jsonObject.getStr("value"));
            });
        } else {
            map.put("value", configByCode.getValue());
        }
        return map;
    }

    public static void main(String[] args) {
        String json = "[{\"value\": \"smtp.qq.com\",\"name\":\"主机\",\"code\":\"host\"},{\"value\": 465,\"name\":\"端口\",\"code\":\"port\"},{\"value\": true,\"name\":\"授权\",\"code\":\"auth\"},{\"value\": \"574847016@qq.com\",\"name\":\"发送者\",\"code\":\"from\"},{\"value\": \"574847016\",\"name\":\"账号\",\"code\":\"user\"},{\"value\": \"pxwrtstibkxlbecj\",\"name\":\"通行证\",\"code\":\"pass\"},{\"value\": true,\"name\":\"SSL启用\",\"code\":\"sslEnable\"}]";
        Map<String, Object> map = new HashMap<>();
        JSONArray array = JSONUtil.parseArray(json);
        array.forEach(item -> {
            JSONObject jsonObject = JSONUtil.parseObj(item);
            map.put(jsonObject.getStr("code"), jsonObject.getStr("value"));
        });
        System.out.println(map);
    }
}
